import i18n from "i18next";
import {
  CHANGE_LANGUAGE,
  ADD_LANGUAGE,
  LanguageActionTYpes,
} from "./languageActions";

/** 定义state接口 */
interface LanguageState {
  language: "en" | "zh";
  languageList: Array<{ name: string; code: string }>;
}

const defaultState: LanguageState = {
  language: "zh",
  languageList: [
    { name: "中文", code: "zh" },
    { name: "English", code: "en" },
  ],
};

// ! 定义了action type 如果参数错误的话 就会报错 (ts的强大之处)
export default (state = defaultState, action: LanguageActionTYpes) => {
  console.log("languageReducer", action);

  // ! 任何store保存的state都是一个immutabled对象,是不可更改的
  // 可以改为switch case

  if (action.type === CHANGE_LANGUAGE) {
    i18n.changeLanguage(action.payload); // 不标准 有副作用
    return { ...state, language: action.payload };
  }

  if (action.type === ADD_LANGUAGE) {
    return { ...state, languageList: [...state.languageList, action.payload] };
  }

  return state; // 返回新state
};
